package com.java2007.hotel.controller;


import com.java2007.hotel.constant.Constant;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 通过反射调佣实际servlet中的方法
 *
 * @author csl
 * @version V1.0
 * @date 2021/01/22
 **/
public class BaseServlet extends HttpServlet {

    /**
     * 重写service方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter(Constant.METHOD);

        if (StringUtils.isNullOrEmpty(method)) {
            resp.getWriter().write(Constant.ERR_PATH);
            return;
        }

        String invoke = null;
        if (null != method) {
            Class<? extends BaseServlet> clazz = this.getClass();
            try {
                Method method1 = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
                if (null == method1) {
                    resp.getWriter().write(Constant.ERR_PATH);
                    return;
                }
                invoke = (String) method1.invoke(this, req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (null != invoke) {
            if (invoke.startsWith(Constant.REDIRECT)) {
                resp.sendRedirect(invoke.substring(invoke.indexOf(Constant.MAO) + 1));
            } else if (invoke.startsWith(Constant.FORWARD)) {
                req.getRequestDispatcher(invoke.substring(invoke.indexOf(Constant.MAO) + 1)).forward(req, resp);
            } else if (invoke.startsWith(Constant.BACK)) {
                resp.getWriter().write(" <script> " +
                        "                        alert(\""+invoke.substring(invoke.indexOf(Constant.MAO) + 1,invoke.indexOf("%"))+"\");" +
                        "location.href=\"http://localhost:8080/Hotel/"+invoke.substring(invoke.indexOf(Constant.BAI) + 1)+"\";\n" +
                        "</script>");
            } else if (invoke.startsWith(Constant.BACK_TEXT)) {
                resp.getWriter().write(invoke.substring(invoke.indexOf(Constant.MAO) + 1));
            } else {
                resp.getWriter().write(Constant.ERR_PATH);
            }
        }

    }
}
